package com.kly.pay.factory;

import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.exception.common.ApplicationException;
import com.kly.enums.PayGatewayEnum;
import com.kly.pay.service.BasicPayActionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 支付初始化
 * @author linqu
 */
@Service
@Slf4j
public class PayServiceFactory {

    private static ConcurrentHashMap<PayGatewayEnum, BasicPayActionService> payProcessMap = new ConcurrentHashMap<>();
    private static ConcurrentHashMap<String, GoogleApiService> googleApiMap = new ConcurrentHashMap<>();

    @Resource
    private ApplicationContext applicationContext;

    @PostConstruct
    public void postConstruct() {

        Map<String, BasicPayActionService> serviceMap =  applicationContext.getBeansOfType(BasicPayActionService.class);
        Map<String, GoogleApiService> payChannel =  applicationContext.getBeansOfType(GoogleApiService.class);

        if (CollectionUtils.isEmpty(serviceMap)) {
            throw new ApplicationException("The payGateway setup failed");
        }
        if (CollectionUtils.isEmpty(payChannel)) {
            throw new ApplicationException("The payChannel setup failed");
        }

        for (Object object : serviceMap.values()) {
            BasicPayActionService processor = (BasicPayActionService) object;
            log.info("PayProcess init success, payType={}, payProcess={}", processor.getPayType(), processor.getClass());
            payProcessMap.put(processor.getPayType(), processor);
        }

        for (Object object : payChannel.values()) {
            GoogleApiService channel = (GoogleApiService) object;
            log.info("PayChannel init success, payType={}, payProcess={}", channel.getPackageName(), channel.getClass());
            googleApiMap.put(channel.getPackageName(), channel);
        }
    }

    public BasicPayActionService buildPayProcess(PayGatewayEnum smsServiceType) {
        return payProcessMap.get(smsServiceType);
    }

    public GoogleApiService buildGooglePayChannel(String packageName) {
        return googleApiMap.get(packageName);
    }
}
